﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LuaInterface;
using System.IO;

namespace NTUTMessagerServer
{
    public class MemberModel
    {
        public List<Member> memberList = new List<Member>();

        public Boolean isValidate(String account, String password) 
        {
            foreach (Member m in memberList) 
            {
                if (account == m.account && password == m.password) 
                {
                    return true;
                }
            }

            return false;
        }

        public void AddMember(String account, String password) 
        {
            Member member = new Member();

            member.account = account;
            member.password = password;

            memberList.Add(member);
        }

        public static String FILE_NAME = "./lua/member/member.lua"; 

        public void LoadMember() 
        {
            Lua lua = new Lua();

            lua.DoFile(FILE_NAME);

            LuaTable AccountTable = lua.GetTable("AccountTable");

            if (AccountTable != null)
            {
                foreach (LuaTable t in AccountTable.Values)
                {
                    Member member = new Member();
                    member.account = t["account"].ToString();
                    member.password = t["password"].ToString();
                    memberList.Add(member);
                }
            }
        }

        public void SaveMember() 
        {
            StreamWriter tw = new StreamWriter(FILE_NAME, false);

            tw.WriteLine("AccountTable =");
            tw.WriteLine("{");

            foreach (Member m in memberList) 
            {
                tw.WriteLine(m.WriteOut());
            }

            tw.WriteLine("}");

            tw.Close();
        }
    }

    public class Member 
    {
        public String account;
        public String password;

        public String WriteOut() 
        {
            return " {[\"account\"] = \"" + account + "\", [\"password\"] = \"" + password + "\" },";
        }
    }
}
